<?php

/**
 * @author Sven-Ove Bjerkan
 * @copyright 2008
 */

class Busstops {
	/**
	* Find all the busstops, ordered by the order the bus arrives at them.
	* @return Array with keys ['the busstopID']['name'] and ['the busstopID']['time'] or -1 on error.
	*/
	public function getBusstops() {
		$query = "SELECT busstopID, busstopName, busstopTime FROM busstop ORDER BY busstopNo";

		$res = DB::singleton()->execSelectQuery($query);
		$dest = array();

		if ($res['numRows'] > 0) {
			for ($i = 0; $i < $res['numRows']; $i++) {
				$dest[$res['result'][$i]['busstopID']]['name'] =
						$res['result'][$i]['busstopName'];
				$dest[$res['result'][$i]['busstopID']]['time'] =
						$res['result'][$i]['busstopTime'];
			}
			return $dest;
		}
		else return -1;
	}

	/**
	 * Get the form to edit/create a busstop.
	 * @param int $ID the ID of the busstop to edit
	 * @param String $name the name of the busstop.
	 * @return the form.
	 */
	public function showForm($ID, $name) {
		return '<form action="" method="POST">
				Holdeplass-navn: <input type="text" name="busstopName" value="'.$name.'">
				<input type="hidden" name="ID" value="'.$ID.'">
				<input type="submit" value="Lagre">
				</form>';
	}

	/**
	 * Delete a busstop and all corresponding orders.
	 * @param int $ID the busstopID.
	 * @return boolean with status of delete.
	 */
	public function deleteBusstop($ID) {
		$ID = (int)$ID;
		if ($ID === 0) return false;

		// Make sure all is deleted, so do it all in one commit
		DB::singleton()->setAutocommit(false);

		$query = array();

		$query[] = "DELETE FROM busstop WHERE busstopID=?";
		$query[sizeof($query)-1] = DB::singleton()->getQuery($query[sizeof($query)-1], array('i'), array($ID));

		$query[] = "DELETE FROM order WHERE startBusstopID=?";
		$query[sizeof($query)-1] = DB::singleton()->getQuery($query[sizeof($query)-1], array('i'), array($ID));

		for ($i = 0; $i < sizeof($query); $i++) {
			DB::singleton()->execDeleteQuery($query[$i]);
		}

		// Commit the queries
		$res = DB::singleton()->commit();

		// If it failed, do a rollback
		if (!$res) {
			DB::singleton()->rollback();
		}

		// Re-enable autocommit
		DB::singleton()->setAutocommit(true);

		return $res;
	}

	/** 
	 * Create a new busstop
	 * @param String $destName the busstop-name.
	 * @return boolean with status of creation.
	 */
	public function createNewBusstop($destName) {
		// Get highest current busstopNo
		$query = "SELECT MAX(busstopNo) as busstopNo FROM busstop";
		$res = DB::singleton()->execSelectQuery($query);
		$busstopNo = $res['result'][0]['busstopNo']+1;

		$query = "INSERT INTO busstop (busstopName, busstopNo)
				VALUES (?, ".$busstopNo.")";
		$query = DB::singleton()->getQuery($query, array('s'), array($destName));

		return DB::singleton()->execInsertQuery($query);
	}

	/**
	 * Update a busstop
	 * @param int $destID the busstopID
	 * @param String $destName the new name of the busstop
	 * @return boolean with status.
	 */
	public function updateBusstop($destID, $destName) {
		$query = "UPDATE busstop SET busstopName=? WHERE busstopID=?";
		$query = DB::singleton()->getQuery($query, array('s', 'i'), array($destName, $destID));

		return DB::singleton()->execUpdateQuery($query);
	}

	/**
	 * Update the order of the busstops.
	 * @param Array $busstops An array with the busstops in their new order
	 * @return boolean with status.
	 */
	public function updateBusstopOrder(array $busstops) {
		require_once('db.class.php');

		// Disable autocomit to make sure all queries are run
		DB::singleton()->setAutocommit(false);

		// Loop to create the update queries
		for ($i = 0; $i < sizeof($_GET['busstops']); $i++) {
			$query = "UPDATE busstop SET busstopNo=? WHERE busstopID=?";
			$query = DB::singleton()->getQuery($query,
					array('i', 'i'), array($i, $busstops[$i]));

			DB::singleton()->execUpdateQuery($query);
		}

		// Do the commit and rollback if failure
		if (!DB::singleton()->commit()) {
			DB::singleton()->rollback();
		}

		DB::singleton()->setAutocommit(true);
	}

	/**
	 * Update the times for each busstop
	 * @param Array $arr the array with the busstops with key 'the busstopID' and value 'the new time in mins'
	 */
	public function updateTimes(array $arr) {
		require_once('db.class.php');

		DB::singleton()->setAutocommit(false);

		foreach ($arr as $key => $value) {
			$query = "UPDATE busstop SET busstopTime=? WHERE busstopID=?";
			$query = DB::singleton()->getQuery($query,
					array('i', 'i'), array($value, $key));

			DB::singleton()->execUpdateQuery($query);
		}

		if (!DB::singleton()->commit()) {
			DB::singleton()->rollback();
		}

		DB::singleton()->setAutocommit(true);
	}
	
	/**
	 * Get the traveltime in mins from the busstopID to the airport
	 * @param int $busstopID The busstop to start from
	 * @return the traveltime in mins or false on failure
	 */
	public function getTraveltimeFrom($busstopID = null) {
		if (!is_null($busstopID)) {
			// Fetch where to start (order)
			$query = "SELECT busstopNo FROM busstop WHERE busstopID=?";
			$query = DB::singleton()->getQuery($query,
						array('i'), array($busstopID));
	
			$res = DB::singleton()->execSelectQuery($query);
			
			if ($res['numRows'] > 0) {
				$startOrder = $res['result'][0]['busstopNo'];	
			}
			else {
				return false;
			}
		}
		else {
			$startOrder = 0;
		}
		
		// Fetch traveltime from that busstop
		$query = "SELECT SUM(busstopTime) as totTrav FROM busstop WHERE busstopNo >= ?";
		$query = DB::singleton()->getQuery($query,
					array('i'), array($startOrder));				

		$res = DB::singleton()->execSelectQuery($query);
			if ($res['numRows'] > 0) {
			return $res['result'][0]['totTrav'];	
		}
		else {
			return false;
		}
	}
	
	/**
	 * Get the name of a busstop
	 * @param int $busstopID the ID of the busstop
	 * @return the name of the busstop of false on failure
	 */
	public function getBusstopName($busstopID) {
		$query = "SELECT busstopName FROM busstop WHERE busstopID=?";
		$query = DB::singleton()->getQuery($query,
					array('i'), array($busstopID));

		$res = DB::singleton()->execSelectQuery($query);
		
		if ($res['numRows'] > 0) {
			return $res['result'][0]['busstopName'];	
		}
		else {
			return false;
		}
	}
}

?>